﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

namespace Defector
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Report : Window
    {

        public int reportNumber;
        public SqlConnection con;
        public int currentUserID;
        int userID;
        int commentID = -1;



        public Report()
        {
            InitializeComponent();
        }

        public void Start()
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT dbo.People.First_Name + ' ' + dbo.People.Last_Name AS Owner, dbo.Softwares.Software_Name, CONVERT(CHAR(12), dbo.Trouble_Report.Date_Submitted, 101) AS Date_Submitted, dbo.Trouble_Report.PersonId, dbo.Trouble_Report.Priority, dbo.Trouble_Report.Status, dbo.Trouble_Report.Description, dbo.Trouble_Report.Headline, dbo.Trouble_Report.SoftwareSoftware_Id,  CONVERT(CHAR(12), dbo.Trouble_Report.Date_Completed, 101) AS Date_Completed FROM dbo.Trouble_Report INNER JOIN dbo.People ON dbo.Trouble_Report.PersonId = dbo.People.Id INNER JOIN dbo.Softwares ON dbo.Trouble_Report.SoftwareSoftware_Id = dbo.Softwares.Software_Id  WHERE (dbo.Trouble_Report.Trouble_Report_Id = " + reportNumber + ")", con);
            cmd.CommandType = CommandType.Text;
            SqlDataReader sqlReader = cmd.ExecuteReader();
            while (sqlReader.Read())
            {
                userID = Convert.ToInt32(sqlReader["personId"].ToString());
                softwareLabel.Content = sqlReader["Software_Name"].ToString();
                headlineBox.Text = sqlReader["Headline"].ToString();
                this.Title += " " + headlineBox.Text;
                descriptionBox.Text = sqlReader["Description"].ToString();
                submittedText.Content = sqlReader["Date_Submitted"].ToString();
                closedText.Content = sqlReader["Date_Completed"].ToString();
                //Set the status combobox
                if (sqlReader["Status"].ToString() == "")
                    statusBox.SelectedIndex = 0;
                else if(sqlReader["Status"].ToString() == "True")
                    statusBox.SelectedIndex = 1;
                else if (sqlReader["Status"].ToString() == "False")
                    statusBox.SelectedIndex = 2;
                ownerBox.SelectedIndex = userID - 1;
                //Set the prioroty box
                String priority = sqlReader["Priority"].ToString();
                if (priority == "Low")
                    priorityBox.SelectedIndex = 1;
                else if(priority == "Medium")
                    priorityBox.SelectedIndex = 2;
                else if (priority == "High")
                    priorityBox.SelectedIndex = 3;
                else if (priority == "Critical")
                    priorityBox.SelectedIndex = 4;

            }
            con.Close();


            //Load data into comments grid
            con.Open();
            cmd = new SqlCommand("SELECT dbo.Comments.Comment_Id AS ID, CONVERT(CHAR(12), dbo.Comments.Date, 101) AS Date, dbo.People.First_Name + ' ' + dbo.People.Last_Name AS Employee, dbo.Comments.Details AS Comment FROM dbo.Comments INNER JOIN dbo.People ON dbo.Comments.PersonId = dbo.People.Id WHERE (dbo.Comments.Trouble_ReportTrouble_Report_Id = " + reportNumber + ")", con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet reportCommentsDS = new DataSet();
            adapter.Fill(reportCommentsDS);
            reportComments.DataContext = reportCommentsDS.Tables[0].DefaultView;
            con.Close();
            loadEmployees();

        }

        public void loadEmployees()
        {
            DataSet ds = new DataSet();
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT Id AS ID, First_Name + ' ' + Last_Name AS Employee FROM dbo.People";
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.SelectCommand = cmd;
                adapter.Fill(ds, "People");

                DataRow nRow = ds.Tables["People"].NewRow();

                //Binding the data to the combobox.
                ownerBox.DataContext = ds.Tables["People"].DefaultView;

                //To display category name (DisplayMember in Visual Studio 2005)
                ownerBox.DisplayMemberPath =
                   ds.Tables["People"].Columns["Employee"].ToString();
                //To store the ID as hidden (ValueMember in Visual Studio 2005)
                ownerBox.SelectedValuePath =
                   ds.Tables["People"].Columns["ID"].ToString();
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while loading software data.");
            }
        }

        //Pop up a report window when the user double clicks the datagridview 
        private void CommentGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            IInputElement element = e.MouseDevice.DirectlyOver;
            if (element != null && element is FrameworkElement)
            {
                if (((FrameworkElement)element).Parent is DataGridCell)
                {
                    var grid = sender as DataGrid;
                    if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
                    {
                        var rowView = grid.SelectedItem as DataRowView;
                        if (rowView != null)
                        {
                            DataRow row = rowView.Row;
                            commentID = Convert.ToInt32(row[0].ToString());
                            commentBox.Text = row[3].ToString();
                        }
                    }
                }
            }
        }

        //Submit new comment
        private void newComment_Click(object sender, RoutedEventArgs e)
        {
            string sqlIns = "INSERT INTO Comments (PersonId, Trouble_ReportTrouble_Report_Id, Date, Details) VALUES (@PersonId, @Trouble_ReportTrouble_Report_Id, @Date, @Details)";

            try
            {
                con.Open();
                SqlCommand cmdIns = new SqlCommand(sqlIns, con);
                cmdIns.Parameters.AddWithValue("@PersonId", currentUserID);
                cmdIns.Parameters.AddWithValue("@Trouble_ReportTrouble_Report_Id", reportNumber);
                cmdIns.Parameters.AddWithValue("@Date", DateTime.Now);
                cmdIns.Parameters.AddWithValue("@Details", commentBox.Text);
                cmdIns.ExecuteNonQuery();
                cmdIns.Dispose();
                cmdIns = null;
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while submitting the comment.");
                throw new Exception(ex.ToString(), ex);
            }

            //Re-load data into comments grid
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT dbo.Comments.Comment_Id AS ID, CONVERT(CHAR(12), dbo.Comments.Date, 101) AS Date, dbo.People.First_Name + ' ' + dbo.People.Last_Name AS Employee, dbo.Comments.Details AS Comment FROM dbo.Comments INNER JOIN dbo.People ON dbo.Comments.PersonId = dbo.People.Id WHERE (dbo.Comments.Trouble_ReportTrouble_Report_Id = " + reportNumber + ")", con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet reportCommentsDS = new DataSet();
            adapter.Fill(reportCommentsDS);
            reportComments.DataContext = reportCommentsDS.Tables[0].DefaultView;
            con.Close();

            commentBox.Text = "";
        }

        private void updateComments_Click(object sender, RoutedEventArgs e)
        {
            if (commentID != -1)
            {
                try
                {
                    con.Open();
                    string updateSql = "UPDATE Comments Set Details = '" + commentBox.Text + "' WHERE dbo.Comments.Comment_Id = " + commentID;

                    SqlCommand UpdateCmd = new SqlCommand(updateSql, con);

                    UpdateCmd.ExecuteNonQuery();
                    con.Close();

                }

                catch (SqlException ex)
                {

                    MessageBox.Show("An error occurred while updating the comment.");
                    throw new Exception(ex.ToString(), ex);

                }

                //Re-load data into comments grid
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT dbo.Comments.Comment_Id AS ID, CONVERT(CHAR(12), dbo.Comments.Date, 101) AS Date, dbo.People.First_Name + ' ' + dbo.People.Last_Name AS Employee, dbo.Comments.Details AS Comment FROM dbo.Comments INNER JOIN dbo.People ON dbo.Comments.PersonId = dbo.People.Id WHERE (dbo.Comments.Trouble_ReportTrouble_Report_Id = " + reportNumber + ")", con);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataSet reportCommentsDS = new DataSet();
                adapter.Fill(reportCommentsDS);
                reportComments.DataContext = reportCommentsDS.Tables[0].DefaultView;
                con.Close();

                commentBox.Text = "";
                commentID = -1;
            }
            else
                MessageBox.Show("No message selected!");
        }

        private void updateReport_Click(object sender, RoutedEventArgs e)
        {
            int status = -1;
            if (statusBox.Text == "New")
                status = -1;
            else if (statusBox.Text == "Open")
                status = 1;
            else if (statusBox.Text == "Closed")
                status = 0;

            try
            {
                con.Open();
                string updateSql = "UPDATE Trouble_Report Set Status = " + status + " WHERE dbo.Trouble_Report.Trouble_Report_Id = " + reportNumber;

                SqlCommand UpdateCmd = new SqlCommand(updateSql, con);

                UpdateCmd.ExecuteNonQuery();

                updateSql = "UPDATE Trouble_Report Set Priority = '" + priorityBox.Text + "' WHERE dbo.Trouble_Report.Trouble_Report_Id = " + reportNumber;

                UpdateCmd = new SqlCommand(updateSql, con);

                UpdateCmd.ExecuteNonQuery();

                updateSql = "UPDATE Trouble_Report Set PersonId = " + (ownerBox.SelectedIndex + 1) + " WHERE dbo.Trouble_Report.Trouble_Report_Id = " + reportNumber;

                UpdateCmd = new SqlCommand(updateSql, con);

                UpdateCmd.ExecuteNonQuery();
                con.Close();

            }

            catch (SqlException ex)
            {

                MessageBox.Show("An error occurred while updating the report.");
                throw new Exception(ex.ToString(), ex);

            }

            MessageBox.Show("Report Updated.");
        }
    }
}
